﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;
using Yule8xCommon.Typelib;
using Yule8xModel;

namespace Yule8xWechat.Login
{
    public partial class LoginCallback : System.Web.UI.Page
    {
        Dictionary<string, string> srcurls;
        protected void Page_Load(object sender, EventArgs e)
        {
            // 微信Code
            string code = RequestUtil.GetString("code");

            // 跳转来源URL
            string src = RequestUtil.GetString("src").ToLower();

            // 推广代理ID
            int referral_id = RequestUtil.GetInteger("referral_id");

            // 设置跳转链接
            this.SetRefererUrls();
            // 检测session
            this.CheckLoginStatus(src);
            // 微信登录
            if (!string.IsNullOrEmpty(code))
            {
                this.WxLogin(code, referral_id);
                if (!string.IsNullOrEmpty(src) && srcurls.Keys.Contains(src))
                {
                    Response.Redirect(srcurls[src], true);
                }
            }
            Response.Write("done" + code);
        }
        void SetRefererUrls()
        {
            // 访问来源跳转
            srcurls = new Dictionary<string, string>();
            srcurls.Add("promotion", "../Promotion/Default.aspx");
            srcurls.Add("agentregist", "../Payment/WxPay/AgentRegistion.aspx");
            srcurls.Add("agent", "../Agent/Index.aspx");
            srcurls.Add("userindex", "../Agent/UserIndex.aspx");
            srcurls.Add("givecard", "../RoomCard/GiveCard.aspx");
            srcurls.Add("buycard", "../Payment/WxPay//BuyCard.aspx");
            srcurls.Add("diamondtransfer", "../Dimond/DimondTransfer.aspx");
            srcurls.Add("recharge", "../Recharge/History.aspx");
            srcurls.Add("withdraw", "../Withdraw/Default.aspx");
        }
        void CheckLoginStatus(string src)
        {
            object loginData = Session["login"];
            WxUserInfoResult wxUser = null;
            if (null != loginData)
            {
                wxUser = loginData as WxUserInfoResult;
            }
            if (null != loginData || null != wxUser)
            {
                if (!string.IsNullOrEmpty(src) && srcurls.Keys.Contains(src))
                {
                    LogUtil.Instance.WriteInfo(string.Format("[LoginCallback] CheckLoginStatus已登录，无需重新获取信息: {0}", JSON.stringify(wxUser)));
                    Response.Redirect(srcurls[src], true);
                }
            }
        }
        void WxLogin(string code, int referral_id)
        {
            string basetoken = WechatUtil.GetToken();
            LogUtil.Instance.WriteInfo("[LoginCallback] WxLogin重新获取信息:basetoken=" + basetoken);
            string errmsg;
            // 通过code换取网页授权access_token
            // 正确:{ "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
            // 错误:{"errcode":40029,"errmsg":"invalid code"}
            string tokenurl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", AppInfo.AppID, AppInfo.AppSecret, code);
            string tokencontent = HttpUtil.HttpGet(tokenurl);
            // 记录日志
            LogUtil.Instance.WriteInfo(string.Format("[LoginCallback] WxLogin重新获取信息: tokenurl={0}, tokencontent={1}", tokenurl, tokencontent));
            if (string.IsNullOrWhiteSpace(tokencontent) || tokencontent.IndexOf("errcode") > -1)
            {
                errmsg = "[LoginCallBack] WxLogin重新获取信息: GetToken,通过code换取网页授权access_token 出错了：" + tokencontent;
                LogUtil.Instance.WriteInfo(errmsg);
                Response.Write(errmsg);
                Response.End();
            }
            WxTokenResult tokenResult = JSON.parse<WxTokenResult>(tokencontent);

            // 刷新token
            // 正确：{ "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
            // 错误：{"errcode":40029,"errmsg":"invalid code"} 
            /*string refreshtokenurl = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}",AppInfo.AppID,tokenResult.refresh_token);
            string refreshtokencontent = HttpUtil.HttpGet(refreshtokenurl);
            if (refreshtokencontent.IndexOf("errcode") > -1)
            {
                errmsg = "RefreshToken出错了：" + refreshtokencontent;
                LogUtil.Instance.WriteLog(errmsg);
                Response.Write(errmsg);
                Response.End();
            }
            tokenResult = JSON.parse<WxTokenResult>(refreshtokencontent);*/

            // 获取用户基本信息（包括UnionID机制）
            // 成功：{ "subscribe": 1, "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", "nickname": "Band", "sex": 1, "language": "zh_CN", "city": "广州", "province": "广东", "country": "中国", "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0", "subscribe_time": 1382694957, "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL" "remark": "", "groupid": 0, "tagid_list": [128, 2]}
            // 错误：{"errcode":40013,"errmsg":"invalid appid"}
            string infourl = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", basetoken, tokenResult.openid);
            string infocontent = HttpUtil.HttpGet(infourl);
            // 记录日志
            LogUtil.Instance.WriteInfo(string.Format("[LoginCallback] infourl={0}, infocontent={1}", infourl, infocontent));

            if (string.IsNullOrWhiteSpace(infocontent) || infocontent.IndexOf("errcode") > -1)
            {
                errmsg = "[LoginCallBack] GetInfo,获取用户基本信息 出错了：" + infocontent;
                LogUtil.Instance.WriteInfo(errmsg);
                Response.Write(errmsg);
                Response.End(); // 输出停止
            }
            // 解析微信返回的用户信息
            WxUserInfoResult wxUser = JSON.parse<WxUserInfoResult>(infocontent);

            LogUtil.Instance.WriteInfo("[LoginCallBack] GetInfo 从微信获取的新鲜的用户资料信息：" + infocontent);

            // 更新用户表字段
            try
            {
                wxUser.user_id = UserModels.WxLoginCallbackUpdateDb(wxUser,referral_id);
                wxUser.game_id_bozhong = UserModels.GetGameID(0, wxUser.unionid, "bozhong", out errmsg); // 泊众游戏userid
                wxUser.game_id_wanghu = UserModels.GetGameID(0, wxUser.unionid, "wanghu", out errmsg); // 网狐游戏gameid
                string sqlstmt = string.Format("select parent1_uid, parent2_uid, realname from t_user where user_id=" + wxUser.user_id);
                System.Data.DataTable dtUserTemp = DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteDataTable(sqlstmt);
                if (null != dtUserTemp || dtUserTemp.Rows.Count > 0)
                {
                    wxUser.parent1_uid = DataTableUtil.GetInteger(dtUserTemp,"parent1_uid");
                    wxUser.parent2_uid = DataTableUtil.GetInteger(dtUserTemp,"parent2_uid");
                    wxUser.realname = DataTableUtil.GetString(dtUserTemp, "realname");
                }

                // 有时候从微信获取用户资料，nickname竟然是空的，这时候需要从数据库判断，如果数据库资料完整，则从数据库读取
                if (wxUser.user_id > 0 && string.IsNullOrEmpty(wxUser.nickname))
                {
                    wxUser = UserModels.GetWxUserInfo(wxUser.user_id);
                    LogUtil.Instance.WriteInfo(string.Format("[LoginCallBack] GetInfo 有时候从微信获取用户资料，nickname竟然是空的：{0}, 这是从新从数据库获取的用户信息:{1}", infocontent, null == wxUser ? "null" : JSON.stringify(wxUser)));
                }
            }
            catch (Exception ex)
            {
                LogUtil.Instance.WriteError("[LoginCallBack-GetInfo] 获取user_id和game_id出错：", ex);
            }

            Session.Add("login", wxUser); // 保存会话消息

            // 记录日志
            LogUtil.Instance.WriteInfo(string.Format("[LoginCallBack] 登录成功 {0}", JSON.stringify(wxUser)));
        }
    }
}